package com.bdqn.qnnews.wemedia.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.qnnews.common.base.ResultCode;
import com.bdqn.qnnews.jwt.utils.JwtTokenUtil;
import com.bdqn.qnnews.rest.exception.ApplicationException;
import com.bdqn.qnnews.wemedia.api.dto.WmUserDto;
import com.bdqn.qnnews.wemedia.convert.WmUserConvert;
import com.bdqn.qnnews.wemedia.entity.WmUser;
import com.bdqn.qnnews.wemedia.mapper.WmUserMapper;
import com.bdqn.qnnews.wemedia.service.WmUserService;
import com.bdqn.qnnews.wemedia.vo.WmLoginReqVo;
import com.bdqn.qnnews.wemedia.vo.WmUserRespVo;
import com.nimbusds.jose.JOSEException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author xlz
 * @since 2023-12-26
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    private final PasswordEncoder passwordEncoder;

    @Override
    public WmUserRespVo login(WmLoginReqVo loginReqVo) {
        // 用户登录
        // 查询用户是否存在
        final QueryWrapper<WmUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", loginReqVo.getName());
        final WmUser user = getOne(queryWrapper);
        // 判断当前用户是否存在
        if (user == null){
            throw new ApplicationException(ResultCode.WM_USER_DATA_NOT_EXIST);
        }
        // 判断密码是否正确,这里需要使用加密工具进行校验
        if (!passwordEncoder.matches(loginReqVo.getPassword(),user.getPassword())){
            throw new ApplicationException(ResultCode.LOGIN_PASSWORD_ERROR);
        }
        // 生成token
        // 将查询得到的entity转换为Dto
        final WmUserDto wmUserDto = WmUserConvert.INSTANCE.entityToDto(user);
        wmUserDto.setPassword("");
        // 将用户信息转换为json字符串后传递给工具类生成token
        try {
            final String token = JwtTokenUtil.generateTokenByRsa(JSONUtil.toJsonStr(wmUserDto), 30*24*60*60);
            // 将token和user对象封装为UserDto
            return new WmUserRespVo(token,wmUserDto);
        } catch (JOSEException e) {
            throw new RuntimeException(e);
        }
    }
}
